<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;

class GitlabHookAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->get('before') == '0' || $request->get('after') == '0') { // 新建分支或者删除分支时 不做部署操作
            \Log::info('新建分支或者删除分支时 不做部署操作', [$request->get('before'), $request->get('after')]);
            abort(Response::HTTP_FORBIDDEN, json_encode(['新建分支或者删除分支时 不做部署操作', $request->get('before'), $request->get('after')]));
        }
        $validator = Validator::make($request->headers->all(), [
            'x-gitlab-event' => 'required',
            'x-gitlab-token' => 'required',
        ]);
        if ($validator->fails()) {
            \Log::info('fails ', $request->headers->all());
            \Log::info('event', ['event' => $request->headers->get('x-gitlab-event')]);
            \Log::info('token', ['token' => $request->headers->get('x-gitlab-token')]);
            abort(Response::HTTP_FORBIDDEN, 'gitlab-token不对');
        }

        if ($request->headers->get('x-gitlab-token') != env('GITLAB_TOKEN')) {
            abort(Response::HTTP_FORBIDDEN, 'GITLAB_TOKEN 不对');
        }

        return $next($request);
    }
}
